package com.srwl.mytx.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.srwl.mytx.R;
import com.srwl.mytx.tao.av.CameraHelper;
import com.srwl.mytx.tao.av.ClipManager;
import com.srwl.mytx.tao.av.FileUtils;
import com.srwl.mytx.tao.av.SystemUtil;
import com.srwl.mytx.tao.av.VideoBean;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.VideoUtil;
import com.srwl.mytx.widget.RecordTimelineView;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

//import com.mabeijianxi.smallvideorecord2.AudioRecorder;
//import com.mabeijianxi.smallvideorecord2.FFMpegUtils;
//import com.mabeijianxi.smallvideorecord2.jniinterface.FFmpegBridge;
//import com.taobao.av.ui.view.recordline.ClipManager;
//import com.taobao.av.ui.view.recordline.VideoBean;
//import com.taobao.av.util.CameraHelper;
//import com.taobao.av.util.FileUtils;
//import com.taobao.av.util.SystemUtil;

//录制一次停止后，就报一下错误，暂时还是使用MediaRecorder 来录制视频吧
//10-09 19:01:26.129 627-2964/? E/SurfaceFlinger: Failed to find layer (SurfaceView - com.srbl.mytx/com.srbl.mytx.activity.FFmpegVideoRecordActivity#0) in layer parent (no-parent).
//    Failed to find layer (Background for - SurfaceView - com.srbl.mytx/com.srbl.mytx.activity.FFmpegVideoRecordActivity#0) in layer parent (no-parent).
//10-09 19:01:26.200 627-1604/? E/BufferQueueProducer: [SurfaceView - com.srbl.mytx/com.srbl.mytx.activity.FFmpegVideoRecordActivity#0] cancelBuffer: BufferQueue has been abandoned
public class FFmpegVideoRecordActivity extends BaseActivity implements SurfaceHolder.Callback, View.OnClickListener, Camera.PreviewCallback {//AudioRecorder.AudioListener, FFmpegBridge.FFmpegStateListener
    private static final String TAG = FFmpegVideoRecordActivity.class.getSimpleName();
    private final int PERMISSION_REQUEST_CODE = 100; //权限申请请求码
    private static int REQUEST_CODE_VIDEO_PLAYER = 101;
    private boolean granted = false;
    private String path;
    private ImageView iv_back; //退出
    private ImageView iv_light; //闪光灯
    private ImageView iv_cameraChoose;// 摄像头选择

    private SurfaceView surfaceView; //显示摄像头预览画面
    private ImageView iv_recorder;  //录制按键
    private ImageView iv_recorPause; //录制暂停：实际上是停止录制，最后的完成录制的时候，是把几个录制的视频片段拼接成一个视频
    private CheckBox cb_deleteVideoClip;//删除最后一个视频片段
    private ImageView iv_commit; //完成视频录制确定按键
    private TextView tv_recordTime;
    private TextView tv_videoTooShort;
    private RecordTimelineView recordTimelineView;
    private ProgressBar progressBar;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private Camera.Parameters parameters;

    private boolean isRecording;//标记是否增长录制
    private Handler mSafeHandler;
    private ClipManager mClipManager; //视频片段管理者，有删除片段等功能
    private int maxDuration = 20000;//视频录制最长时间 20s 视频差不多是2M多
    private int minDuration = 3000;
    private int currentDuration = 0;
    private StringBuilder mFormatBuilder;
    private Formatter mFormatter;
    private Runnable _runnableTimer;
    private long startTime;
    private int mVideoIndex = -1;//视频片段索引
    private String dir;//视频存储路径
    private String jpegPath;//封面图片路径
    private Animation scaleAnimation;
    private Animation alpahAnimation;
    private Camera.Size optimalSize;//最优预览尺寸
    private long lastRecordClickTime;
    private int cameraPosition;
    private List<String> clipPaths = new ArrayList<>();
   // private AudioRecorder mAudioRecorder;//音频录制
    private boolean isdecoding;//FFmpeg是否在解码 标记
    private boolean isWaitCombineClip;//是否等待合并视频


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_recorder);
        initView();
        initClipManager();
        alpahAnimation = AnimationUtils.loadAnimation(this, R.anim.taorecorder_alpha_reverse);
        scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.taorecorder_scale_reverse);

        cameraPosition = SystemUtil.getCameraFacingBack();//第一次开启后面的摄像头
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
        initTimer();
        dir = this.getExternalCacheDir().getAbsolutePath() + File.separator + "short_video";
        jpegPath = this.getCacheDir().getAbsolutePath() + File.separator + "taorecorder_video/temp_cover.jpg";
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
      //FFmpegBridge.registFFmpegStateListener(this);
    }

    private void initTimer() {
        //本来我想在用Timer  TimerTask,但是考虑到TimerTask是非Ui线程，每次更新ui还得用handler,或者runOnUiThread,可能性能还不如这个Runnable，但是用Timer 逻辑更清晰，
        _runnableTimer = new Runnable() {
            public void run() {

                if (startTime == 0L && !isRecording) {
                    getSafeHandler().postDelayed(this, 25L);
                } else {
                    if (startTime == 0L) {
                        startTime = System.currentTimeMillis();
                    }
                    long currentClipDuration = (System.currentTimeMillis() - startTime);
                    recordTimelineView.setDuration((int) currentClipDuration);//设置当前视频片段的长度
                    mClipManager.onRecordFrame(currentClipDuration);
                    setRecordTime();
                    if (mClipManager.isMinDurationReached()) {
                        iv_commit.setVisibility(View.VISIBLE);
                    }

                    if (mClipManager.isMaxDurationReached()) {
                        stopRecord();
                    } else {
                        getSafeHandler().postDelayed(this, 25L);
                    }
                }

            }
        };
    }

    /**
     * 初始化视频片段管理器
     */
    private void initClipManager() {
        mClipManager = new ClipManager();
        mClipManager.setMaxDuration(maxDuration);
        mClipManager.setMinDuration(minDuration);
    }

    private void initView() {
        iv_back = findViewById(R.id.iv_back);
        iv_light = findViewById(R.id.iv_light);
        iv_cameraChoose = findViewById(R.id.iv_camera_choose);
        surfaceView = findViewById(R.id.camera_view);
        iv_recorder = findViewById(R.id.iv_recorder);
        cb_deleteVideoClip = findViewById(R.id.btn_delete_last_clip);
        iv_recorPause = findViewById(R.id.iv_record_pause);
        iv_commit = findViewById(R.id.iv_commit);
        tv_videoTooShort = findViewById(R.id.tv_video_too_short);
        tv_videoTooShort.setAlpha(0f);
        tv_recordTime = findViewById(R.id.tv_record_time);
        recordTimelineView = findViewById(R.id.record_time_line);
        progressBar = findViewById(R.id.progress_bar);
        recordTimelineView.setMaxDuration(maxDuration);
        recordTimelineView.setMinDuration(minDuration);
        recordTimelineView.setColor(R.color.holo_red_light, R.color.yancy_indigo600, R.color.common_white, R.color.half_transparent_white);
        iv_back.setOnClickListener(this);
        iv_light.setOnClickListener(this);
        iv_cameraChoose.setOnClickListener(this);
        iv_recorder.setOnClickListener(this);
        cb_deleteVideoClip.setOnClickListener(this);
        iv_commit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPress();

                break;
            case R.id.iv_light:
                changeLight();

                break;
            case R.id.iv_camera_choose:
                rotateCamera();
                break;

            case R.id.iv_recorder:

                Long currentTime = System.currentTimeMillis();
                if (currentTime - lastRecordClickTime < 500) {//防止误击
                    return;
                }
                lastRecordClickTime = currentTime;
                if (isRecording) {
                    stopRecord();
                } else {
                    startRecord();
                }

                break;
            case R.id.btn_delete_last_clip:

                if (cb_deleteVideoClip.isChecked()) {//点一次，选中状态：显示最后一段视频被选中
                    recordTimelineView.selectLast();
                    cb_deleteVideoClip.setChecked(true);
                } else { //再点一次，未选中状态：删除
                    mClipManager.removeLastClip();
                    recordTimelineView.deleteLast();
                    cb_deleteVideoClip.setChecked(false);
                    cb_deleteVideoClip.setEnabled(mClipManager.isUnEmpty());
                    int totalRecordTime = mClipManager.getDuration();
                    if (totalRecordTime < minDuration) {
                        iv_commit.setVisibility(View.GONE);
                    }
                    setRecordTime();
                    clipPaths.remove(mVideoIndex);
                    mVideoIndex--;
                }
                break;
            case R.id.iv_commit:
                if (!isdecoding) {
                    combineClip();
                } else {
                    Log.d(TAG, "视频解码中...");
                    isWaitCombineClip = true;
                    showProgress();
                }

        }
    }

    private void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    /**
     * 显示界面上的录像时间
     */
    private void setRecordTime() {
        int totaltime = mClipManager.getDuration();

        if (totaltime >= 0 && totaltime < maxDuration) {
            mFormatBuilder.setLength(0);
            String stime = mFormatter.format("%d.%d 秒", totaltime / 1000, totaltime / 100 % 10).toString();
            tv_recordTime.setText(stime);
        }

    }

    //闪光灯设置切换
    private void changeLight() {
        Camera.Parameters parameters = camera.getParameters();
        if (CameraHelper.getFlashlightOn(parameters)) {
            CameraHelper.setFlashlightMode(parameters, false);
            iv_light.setImageResource(R.drawable.aliwx_sv_wx_shiny_nor);
        } else {
            CameraHelper.setFlashlightMode(parameters, true);
            iv_light.setImageResource(R.drawable.aliwx_sv_wx_shiny_pre);
        }

        camera.setParameters(parameters);
    }

    private void rotateCamera() {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        int cameraCount = Camera.getNumberOfCameras();

        for (int i = 0; i < cameraCount; ++i) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraPosition == SystemUtil.getCameraFacingBack()) {
                if (cameraInfo.facing == SystemUtil.getCameraFacingFront()) {
                    relaeaseCamera();
                    cameraPosition = SystemUtil.getCameraFacingFront();
                    startPreview();
                    iv_light.setVisibility(View.INVISIBLE);
                    iv_cameraChoose.setImageResource(R.drawable.aliwx_sv_wx_camera_pre);

                    break;
                }
            } else if (cameraInfo.facing == SystemUtil.getCameraFacingBack()) {

                relaeaseCamera();
                cameraPosition = SystemUtil.getCameraFacingBack();
                startPreview();
                iv_light.setImageResource(R.drawable.aliwx_sv_wx_shiny_nor);
                iv_cameraChoose.setImageResource(R.drawable.aliwx_sv_wx_camera_nor);
                break;
            }
        }

    }

    /**
     * 释放Camera
     */
    private void relaeaseCamera() {
//        if (surfaceHolder != null) {
//            surfaceHolder.removeCallback(this);
//        }
        if (camera != null) {
            camera.stopPreview();
            try {
                camera.setPreviewDisplay(null);
                camera.setPreviewCallback(null);

            } catch (IOException e) {
                e.printStackTrace();
            }
            camera.release();
            camera = null;
        }
    }

    public boolean checkIsUnSupportFlishLight(Camera camera) {
//        return Util.hasFlash(camera);
        return false;
    }

    private void relaeaseMediaRecorder() {
        //FFmpegBridge.unRegistFFmpegStateListener(this);
        //FFmpegBridge.nativeRelease();

    }

    public void startRecord() {

        iv_recorder.startAnimation(alpahAnimation);//显示呼吸效果动画
        iv_recorPause.setVisibility(View.VISIBLE);//显示暂停图标
        iv_commit.setEnabled(false);//录制过程中禁用 提交按键
        iv_cameraChoose.setVisibility(View.INVISIBLE);//录制过程中隐藏 摄像头切换按键
        cb_deleteVideoClip.setVisibility(View.VISIBLE);
        cb_deleteVideoClip.setEnabled(false);
        //每次开始录像，生成一个VideoBean，添加进ClipManager
        VideoBean vb = new VideoBean();
        mVideoIndex++;//每录制一段视频，索引增加一次，
        String clipPath = dir + File.separator + "temp_" + mVideoIndex + ".mp4";
        vb.videoFile = clipPath;
        mClipManager.onRecordStarted(vb);
        clipPaths.add(clipPath);
        //重置录像的开始时间点
        startTime = 0L;
        //开始记录录像时间
        getSafeHandler().post(_runnableTimer);

        int vCustomFormat;
//        if (cameraPosition == SystemUtil.getCameraFacingFront()) {
//            vCustomFormat = FFmpegBridge.ROTATE_270_CROP_LT_MIRROR_LR;
//        } else {
//            vCustomFormat = FFmpegBridge.ROTATE_90_CROP_LT;
//        }
//        FFmpegBridge.prepareJXFFmpegEncoder(dir, getCurrentClipName(), vCustomFormat, optimalSize.width, optimalSize.height, 864, 480, 20, 700000);
//        if (mAudioRecorder == null) {
//            mAudioRecorder = new AudioRecorder(this);
//            mAudioRecorder.start();
//        }
        isRecording = true;
        isdecoding = true;
    }

    private String getCurrentClipName() {
        return "temp_" + mVideoIndex;
    }

    public void stopRecord() {
        if (maxDuration - mClipManager.getDuration() < 100) {//禁用录制按键
            iv_recorder.setEnabled(false);
            iv_recorder.setAlpha(0.5f);
        }
        iv_commit.setEnabled(true);
        iv_cameraChoose.setVisibility(View.VISIBLE);
        iv_recorder.clearAnimation();//清除动画
        iv_recorPause.setVisibility(View.INVISIBLE);//隐藏暂停图标
        mClipManager.onRecordPaused();
        if (mSafeHandler != null) {
            getSafeHandler().removeCallbacks(_runnableTimer);
        }

        recordTimelineView.clipComplete();
        isRecording = false;//标记录制停止
        //FFmpegBridge.recordEnd();//通知FFmpeg 底层，停止录制

        cb_deleteVideoClip.setEnabled(mClipManager.isUnEmpty());
    }


    private Handler getSafeHandler() {
        if (mSafeHandler != null) {
            return mSafeHandler;
        } else {
            mSafeHandler = new Handler();
            return mSafeHandler;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //全屏显示
        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        } else {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(option);
        }
        getPermissions();
    }

    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                //具有权限
                granted = true;
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
                granted = false;
            }
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                if (!writeGranted) {
                    size++;
                }
                //录音权限
                int recordPermissionResult = grantResults[1];
                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!recordPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
                    granted = true;

                } else {
                    showToast("请到设置-权限管理中开启");
                    finish();
                }
            }
        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated执行了");
        surfaceHolder = holder;
        startPreview();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d(TAG, "surfaceChanged:" + width + "    " + height);
     surfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d(TAG, "surfaceDestroyed执行了");
        relaeaseCamera();
    }

    private void startPreview() {
        camera = Camera.open(cameraPosition);

        camera.setDisplayOrientation(90);
        try {
            camera.setPreviewDisplay(surfaceHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        parameters = camera.getParameters();
        List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
        List<Camera.Size> videoSizes = parameters.getSupportedVideoSizes();
        // optimalSize = getOptimalVideoSize(videoSizes, previewSizes, surfaceView.getWidth(), surfaceView.getHeight()); //这个方法返回适合的、最高分辨率的Size，
        // 因为现在用的是别人开源的基于FFmpeg的视频录制moudle ，帧数据是camera的回调中获取，所以预览的Size得和录制的视频Szie 一样，不然录制出来是花屏的，应该是用的这个 开源moudle 里面的问题，
        setupPreviewSize(parameters);
        parameters.setPreviewFormat(ImageFormat.YV12);
        Log.d(TAG, "最优尺寸：" + optimalSize.width + "  " + optimalSize.height);
        parameters.setPreviewSize(optimalSize.width, optimalSize.height);
        parameters.set("orientation", "portrait");
        List<String> focusModes = parameters.getSupportedFocusModes();
        //设置自动对焦模式
        if (focusModes.contains("continuous-video")) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        }
        if (checkIsUnSupportFlishLight(camera)) {//如果不支持闪光灯，就隐藏闪光灯切换图标
            iv_light.setVisibility(View.VISIBLE);
        }

        int buffSize = optimalSize.width * optimalSize.height * 3 / 2;
        camera.addCallbackBuffer(new byte[buffSize]);//FFmpeg 录制视频开源作者demo里面说这样才不丢帧 ？？？？？？？
//         camera.addCallbackBuffer(new byte[buffSize]);
//         camera.addCallbackBuffer(new byte[buffSize]);
        camera.setPreviewCallbackWithBuffer(this);
       // parameters.setPreviewFrameRate(20);
        camera.setParameters(parameters);
        camera.startPreview();
    }


    public Camera.Size getOptimalVideoSize(List<Camera.Size> supportedVideoSizes,
                                           List<Camera.Size> previewSizes, int w, int h) {
// Use a very small tolerance because we want an exact match.
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;

// Supported video sizes list might be null, it means that we are allowed to use the preview
// sizes
        List<Camera.Size> videoSizes;
        if (supportedVideoSizes != null) {
            videoSizes = supportedVideoSizes;
        } else {
            videoSizes = previewSizes;
        }
        Camera.Size optimalSize = null;

// Start with max value and refine as we iterate over available video sizes. This is the
// minimum difference between view and camera height.
        double minDiff = Double.MAX_VALUE;

// Target view height
        int targetHeight = h;

// Try to find a video size that matches aspect ratio and the target view size.
// Iterate over all available sizes and pick the largest size that can fit in the view and
// still maintain the aspect ratio.
        for (Camera.Size size : videoSizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

// Cannot find video size that matches the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : videoSizes) {
                if (Math.abs(size.height - targetHeight) < minDiff && previewSizes.contains(size)) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    /**
     * 合并视频
     */
    private void combineClip() {


        (new Thread(new Runnable() {
            public void run() {
                //  String[] input = new String[mVideoIndex];
                StringBuilder param = new StringBuilder();

//                for (int i = 0; i < mVideoIndex; ++i) {
//                    //  input[i] = dir + File.separator + "temp_" + i + ".mp4";
//                    //  videoPathList.add(dir + File.separator + "temp_" + i + ".mp4");
//
//                        param.append("file  '"+ dir + File.separator + "temp_" + i + ".mp4' \r\n");
//
//                }

                for (String clipPath : clipPaths) {
                    param.append("file  '" + clipPath + "' \r\n");
                }

                final String tempVideoPath = dir + File.separator + "temp_output.mp4";
                FileUtils.deleteFile(tempVideoPath);

                VideoUtil.appendMp4List(clipPaths, tempVideoPath);//mp4parser
                hideProgressBar();
                toPlayerActivity(tempVideoPath);
                //ffmpeg -i "concat:input1.mpg|input2.mpg|input3.mpg" -c copy output.mpg

//                String sourcePath = dir + File.separator + "temp_source_path.txt";
//                TextUtil.createText(sourcePath, param.toString());
//                // String[] cmd = {"-f", "concat", "-safe", "0", "-i", sourcePath, "-c", "copy", tempVideoPath};
//                String cmd = String.format("ffmpeg -f concat -safe 0 -i %S -c copy %s", sourcePath, tempVideoPath);
//                int resoutCode = FFmpegBridge.jxFFmpegCMDRun(cmd);
//                if (resoutCode == 0) {
//                    Log.d(TAG, "合并视频成功");
//                    toPlayerActivity(tempVideoPath);
//                }else {
//                    Log.e(TAG, "FFmpeg合并视频失败" );
//                }
//                FFmpeg ffmpeg = FFmpeg.getInstance(FFmpegVideoRecordActivity.this);
//                try {
//                    ffmpeg.execute(cmd, new FFmpegExecuteResponseHandler() {
//                        @Override
//                        public void onSuccess(String message) {
//                            Log.d(TAG, "合并视频成功" + message);
//                            toPlayerActivity(tempVideoPath);
//                        }
//
//                        @Override
//                        public void onProgress(String message) {
//                            Log.d(TAG, "FFmpeg合并视频执行中。。。。。。。。。。");
//                        }
//
//                        @Override
//                        public void onFailure(String message) {
//                            Log.e(TAG, "FFmpeg合并视频失败" + message);
//                        }
//
//                        @Override
//                        public void onStart() {
//                            Log.d(TAG, "FFmpeg合并视频开始");
//                        }
//
//                        @Override
//                        public void onFinish() {
//                            Log.d(TAG, "FFmpeg合并视频结束");
//                        }
//                    });
//                } catch (FFmpegCommandAlreadyRunningException e) {
//                    e.printStackTrace();
//                }
                //   toPlayerActivity(tempVideoPath);
            }
        })).start();
    }

    void hideProgressBar() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (progressBar.isShown()) {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });
    }

    private void toPlayerActivity(String tempVideoPath) {
        String UUIDString = UUID.randomUUID().toString().replaceAll("-", "");
        final String targetVideoPath = dir + File.separator + UUIDString + "_output.mp4";
        final String targetJpgPath = dir + File.separator + UUIDString + "_output.jpg";
        Bitmap thumbnailBitmap = ThumbnailUtils.createVideoThumbnail(tempVideoPath, MediaStore.Video.Thumbnails.MICRO_KIND);//生成封面缩微图
        IMFileTools.writeBitmap(targetJpgPath, thumbnailBitmap, 100);
        //FFMpegUtils.captureThumbnails(tempVideoPath, targetJpgPath, "1");
        //  Bitmap thumbnailBitmap = getVideoThumb(tempVideoPath);
        //复制文件
        //  FileUtils.copyFile(jpegPath, targetJpgPath);
        FileUtils.copyFile(tempVideoPath, targetVideoPath);

        getSafeHandler().post(new Runnable() {
            public void run() {

                // Bundle bundle = getIntent().getExtras();
                Bundle bundle = new Bundle();
                BigDecimal duration = new BigDecimal(mClipManager.getDuration());
                BigDecimal ms = new BigDecimal(1000);
                int returnValue = duration.divide(ms, 0, 1).intValue();
                bundle.putInt("videoDuration", returnValue);


                BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
                decodeOptions.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(targetJpgPath, decodeOptions);
                int actualWidth = decodeOptions.outWidth;
                int actualHeight = decodeOptions.outHeight;


                int size = 0;
                if ((new File(targetVideoPath)).isFile()) {
                    File file = new File(targetVideoPath);
                    size = (int) file.length();
                }

                bundle.putInt("framePicWidth", actualWidth);
                bundle.putInt("framePicHeight", actualHeight);
                bundle.putInt("videoSize", size);
//                IMCommitManager.commitEvent("Finish_Record", "Page_WangXin_VideoRecord", (long) mClipManager.getDuration(), "size", Integer.toString(size));
                bundle.putCharSequence("videoPath", targetVideoPath);
                bundle.putCharSequence("framePicPath", targetJpgPath);
                bundle.putCharSequence("uploadID", getIntent().getStringExtra("uploadID"));
                bundle.putCharSequence("uploadTarget", getIntent().getStringExtra("uploadTarget"));

                Intent intent = new Intent(FFmpegVideoRecordActivity.this, MyVideoPlayActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_VIDEO_PLAYER);
                overridePendingTransition(R.anim.taorecorder_push_left_in, R.anim.taorecorder_push_left_out);


            }
        });
    }

    private Bitmap getVideoThumb(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return media.getFrameAtTime();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (isRecording) {
            stopRecord();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        relaeaseMediaRecorder();
        if (alpahAnimation != null) {
            alpahAnimation.cancel();
            alpahAnimation.reset();
            alpahAnimation = null;
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPress();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void onBackPress() {
        if (isRecording) {
            return;
        }
        if (mClipManager.isUnEmpty()) {
            new AlertDialog.Builder(this)
                    .setTitle("提醒")
                    .setMessage("确定放弃已经录制的视频?")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            clearTempFiles(dir);
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE_VIDEO_PLAYER == requestCode) {
            if (RESULT_OK == resultCode) {
                setResult(-1, data);
                finish();
            }
        }
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        camera.addCallbackBuffer(data);
        if (isRecording) {
           // FFmpegBridge.encodeFrame2H264(data);//视频数据传给FFmpeg底层

        }
    }

//    @Override
//    public void onAudioError(int what, String message) {
//
//    }
//
//    @Override
//    public void receiveAudioData(byte[] sampleBuffer, int len) {
//        if (isRecording && len > 0) {
//           // FFmpegBridge.encodeFrame2AAC(sampleBuffer);
//        }
//    }

    private void setupPreviewSize(Camera.Parameters camera_params) {
        Camera.Size valid_size = null;
        if (valid_size == null) {
            Camera.Size[] size_list = CameraHelper.choosePreviewSize(camera_params, 864, 480);
            if (size_list.length == 0) {
                valid_size = camera_params.getPreviewSize();
            } else {
                valid_size = size_list[0];
            }
        }

        optimalSize = valid_size;
        camera_params.setPreviewSize(valid_size.width, valid_size.height);
    }

    public void clearTempFiles(String videoPath) {

        File dir = new File(videoPath);
        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            File[] arr$ = files;
            int len$ = files.length;

            for (int i$ = 0; i$ < len$; ++i$) {
                File file = arr$[i$];
                if (!file.isDirectory()) {
                    String filename = file.getName();
                    if (filename.startsWith("temp_")) {//(filename.endsWith(".mp4")||filename.endsWith(".h264") ||filename.endsWith(".aac") ) &&
                        file.delete();
                    }
                }
            }
        }


    }

//    @Override
//    public void allRecordEnd() {//当所有视频处理完成，触发该监听
//
//        Log.d(TAG, "所有视频处理完成");
//        isdecoding = false;
//        if (isWaitCombineClip) {
//            combineClip();
//        }
//
//    }
}
